import uvicorn
import sys
import subprocess
import os
import time
import threading
import signal

sys.dont_write_bytecode = True

# 全局变量，用于存储Vue进程
vue_process = None

def start_vue_project():
    global vue_process
    current_dir = os.path.dirname(os.path.abspath(__file__))
    vue_project_dir = os.path.join(current_dir, "vue-project")
    
    print(f"正在启动 Vue 项目... 路径: {vue_project_dir}")
    
    # 修改：不捕获输出，避免缓冲区阻塞
    vue_process = subprocess.Popen(
        "npm run dev",
        cwd=vue_project_dir,
        shell=True,
        # 不捕获输出，让输出直接显示在终端
        stdout=None,
        stderr=None
    )
    
    # 给Vue项目一些启动时间
    time.sleep(3)
    
    # 检查进程是否仍在运行
    if vue_process.poll() is not None:
        print("Vue 项目启动失败")
        return False
    
    print("Vue 项目启动成功")
    return True

def signal_handler(sig, frame):
    """处理Ctrl+C信号，确保Vue进程被正确关闭"""
    global vue_process
    print("\n正在停止服务...")
    if vue_process:
        print("正在停止 Vue 项目...")
        vue_process.terminate()
        try:
            vue_process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            vue_process.kill()
    print("服务已停止")
    sys.exit(0)

if __name__ == "__main__":
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    
    # 启动 Vue 项目
    if not start_vue_project():
        sys.exit(1)
    
    try:
        # 启动 FastAPI 应用
        print("正在启动 FastAPI 应用...")
        uvicorn.run(
            "fastapiApp:app", 
            host="0.0.0.0", 
            port=7777, 
            reload=True,
            reload_dirs=[
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "fastapiApp"),
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "fastapiApp", "core"),
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "fastapiApp", "utils")
            ],
            factory=False
        )
    except KeyboardInterrupt:
        # 这里实际上不会执行到，因为信号处理器会处理Ctrl+C
        pass
    finally:
        # 停止 Vue 进程
        if vue_process:
            print("正在停止 Vue 项目...")
            vue_process.terminate()
            try:
                vue_process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                vue_process.kill()
